package com.zzzzzz.content.tag;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.zzzzzz.content.topictag.TopicTag;
import com.zzzzzz.content.topictag.TopicTagDao;

@Service("tagService")
public class TagServiceImpl implements TagService {
	@Resource
	private TagDao tagDao;
	@Resource
	private TopicTagDao topicTagDao;
	
	@Transactional
	public void updateTagByAddTopic(Long topicId,String tags){
		List<String> tagList = getTagList(tags);
		for (String tagName : tagList) {
			Integer tagId = tagDao.findIdByName(tagName);
			if(tagId != null){
				tagDao.editReferCountById(tagId, 1);
			}else{
				Tag tag = new Tag();
				tag.setName(tagName);
				tagDao.add(tag);
				tagId = tag.getId();
			}
			TopicTag topicTag = new TopicTag(topicId, tagId);
			topicTagDao.add(topicTag);
		}
	}
	
	@Transactional
	public void updateTagByDelTopic(Long topicId,String tags){
		List<String> tagList = getTagList(tags);
		for (String tagName : tagList) {
			Tag tag = tagDao.findByName(tagName);
			if(tag != null){
				if(tag.getReferCount()<=1){
					tagDao.delById(tag.getId());
				}else{
					tagDao.editReferCountById(tag.getId(), -1);
				}
			}
			topicTagDao.delByTopicIdAndTagId(topicId,tag.getId());
		}
	}
	
	@Transactional
	public void updateTagByEditTopic(Long topicId,String tags){
		List<String> requestTagList = getTagList(tags);
		List<String> tagList = topicTagDao.findTagNameByTopicId(topicId);
		
		List<String> removedList = new ArrayList<String>();
		for(String tagName : tagList){
			boolean isRepeat = false;
			for(String requestTagName : requestTagList){
				if(tagName.equalsIgnoreCase(requestTagName)){
					isRepeat = true;
					break;
				}
			}
			if(isRepeat) {
				removedList.add(tagName);
			}
		}
		
		tagList.remove(removedList);
		requestTagList.remove(removedList);
		
		this.updateTagByDelTopic(topicId, getTags(tagList));
		this.updateTagByAddTopic(topicId, getTags(requestTagList));
	}
	
	private List<String> getTagList(String tags){
		tags = StringUtils.replace(tags, ",", "，");
		Iterable<String> tagIterable = Splitter.on('，').omitEmptyStrings().trimResults().split(tags);
		List<String> tagList = Lists.newArrayList(tagIterable);
		return tagList;
	}
	private String getTags(List<String> tagList){
		return Joiner.on("， ").join(tagList);
	}
}
